<template>
  <div>
    <div
      v-show="!checkedList.length"
      class="table-choose-box flex"
      style="flex-wrap: nowrap"
    >
      <ul class="set flex">
        <li v-if="routeName === 'seriesOverview'">
          <span class="title"> 广告组 </span>
          <div>
            <el-select
              v-model="queryData.adgroupId"
              placeholder="请选择广告组"
              size="small"
              style="width: 110px"
              @change="queryDataChange"
            >
              <el-option label="全部广告组" value="" />
              <el-option
                v-for="(item, index) in allAdList"
                :key="item.adGroupId"
                :label="item.name"
                :value="item.adGroupId"
              />
            </el-select>
          </div>
        </li>
        <li>
          <span class="title"> 匹配类型 </span>
          <div>
            <el-select
              v-model="queryData.matchType"
              placeholder="请选择"
              size="small"
              style="width: 100px"
              @change="queryDataChange"
            >
              <el-option label="全部类型" value="" />
              <el-option label="模糊匹配" value="BROAD" />
              <el-option label="精确匹配" value="EXACT" />
            </el-select>
          </div>
        </li>

        <li>
          <powerSearch
            class="btn"
            :query-data="{ ...queryData.reportKeywordListCondition }"
            @click.native="highSearchShow = true"
          ></powerSearch>
        </li>
      </ul>
      <div />

      <div class="handle flex">
        <div style="width: 120px">
          <el-input
            v-model="queryData.name"
            size="small"
            placeholder="搜索关键词"
            @keyup.enter.native="queryDataChange"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="queryDataChange"
            />
          </el-input>
        </div>

        <em
          v-if="
            !this.$isReadOnly(this.$store.state.user.userInfo.roleName) &&
            caInfo.displayStatus !== 'DELETED' &&
            adInfo.displaystatus !== 'DELETED'
          "
          @click="handleShowAddKey('add')"
          >添加关键词</em
        >
        <em
          v-if="
            !this.$isReadOnly(this.$store.state.user.userInfo.roleName) &&
            caInfo.displayStatus !== 'DELETED' &&
            adInfo.displaystatus !== 'DELETED'
          "
          @click="handleShowAddKey('upload')"
          >上传关键词</em
        >
        <em @click="thShowChange">设置显示字段</em>
        <em @click="dowLoadCsv">导出数据</em>
      </div>
    </div>

    <table-batch-handle
      v-show="checkedList.length"
      :num="checkedList.length"
      :del-show="false"
      @batchStart="handleBatchStartOrPause('ACTIVE')"
      @batchPause="handleBatchStartOrPause('PAUSED')"
    >
      <el-popover
        v-model="popoShow"
        placement="bottom"
        width="430"
        @show="handlerPopoShow"
      >
        <adjustBox
          ref="adjustBox"
          v-loading="adJustLoading"
          @handlerCancel="popoShow = false"
          @handlerSub="changeFeiYong"
        ></adjustBox>
        <em
          slot="reference"
          class="pointer"
          style="font-size: 14px; margin: 0 14px; padding-left: 20px"
          >批量修改最高每次点击费用</em
        >
      </el-popover>
    </table-batch-handle>

    <el-table
      ref="keyTable"
      v-loading="loading"
      :element-loading-text="loadingText"
      :data="tableData"
      style="width: 100%; margin-top: 14px"
      show-summary
      class="series-table"
      sortable="custom"
      :summary-method="returnTotal"
      :header-cell-class-name="headerStyle"
      @selection-change="tableCheckChange"
      @sort-change="tableSortChange"
    >
      >
      <el-table-column
        v-if="
          selectBtnShow &&
          caInfo.displayStatus !== 'DELETED' &&
          adInfo.displaystatus !== 'DELETED'
        "
        type="selection"
        width="45"
      />
      <el-table-column label="关键词" prop="text" width="220" fixed="left">
        <template slot-scope="scope">
          <div
            class="pointer"
            @click="handleOneKeyShow(scope.row)"
            v-html="replaceKeyWord(scope.row.text, scope.row.matchType)"
          ></div>
        </template>
      </el-table-column>

      <el-table-column
        v-if="routeName === 'seriesOverview'"
        label="广告组"
        width="200"
      >
        <template slot-scope="scope">
          <div
            class="pointer overflow-ellipsis"
            @click="handlePush(scope.row.adGroupId)"
          >
            {{ scope.row.adGroupName }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="180" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.campaignDisplayStatus === 'ON_HOLD'">
            <i class="yellow-color status-dot" /> <span>广告系列暂缓</span>
          </div>
          <div v-else>
              <p
                v-if="scope.row.campaignDisplayStatus === 'PAUSED'"
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <i class="yellow-color status-dot" /> <span>关键词暂停</span>
              </p>
              <div v-else>
                <!-- 判断苹果状态 -->
                <p
                  v-if="scope.row.status === 'ACTIVE'"
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  "
                >
                  <i class="liu-color status-dot" /><span>开启中</span>
                </p>

                <p
                  v-else
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  "
                >
                  <i class="hui-color status-dot" /> <span>暂停中</span>
                </p>
              </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="false" label="出价优势" width="180" align="center">
        <template />
      </el-table-column>
      <template v-for="item in thListCopy">
        <el-table-column
          v-if="item.show"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
          :sortable="item.sort"
          :width="item.width || 120"
          :align="item.align || 'right'"
        >
          <template slot-scope="scope">
            <div v-if="item.prop === 'matchType'">
              <span class="keyWord_right">{{
                scope.row.matchType === "EXACT" ? "精确匹配" : "模糊匹配"
              }}</span>
            </div>
            <div v-else>
              <div
                v-if="item.showSta && caInfo.displayStatus !== 'DELETED'"
                :class="
                  item.prop === 'bidAmount' && showStatus
                    ? 'price_div'
                    : 'price_no'
                "
                @click="openEdit(item.prop, scope.$index)"
              >
                <span
                  v-if="
                    item.pre &&
                    !(
                      item.prop === 'bidAmount' && scope.$index === index_number
                    )
                  "
                >
                  <span class="keyWord_right">{{ unitTxt }}</span>
                  <span class="keyWord_right">{{
                    scope.row[item.prop] | $toFixed(2)
                  }}</span>
                </span>
                <el-input
                  v-if="
                    item.prop === 'bidAmount' && scope.$index === index_number
                  "
                  v-model="scope.row[item.prop]"
                  v-focus
                  size="small"
                  @blur="editYS(scope.row, scope.$index)"
                  @input="isChange"
                  @keyup.enter.native="editYS(scope.row, scope.$index)"
                  @focus="handleFocus(scope.row)"
                ></el-input>
                <span v-if="item.suf">{{ item.suf }}</span>
              </div>
              <div v-else>
                <span v-if="item.pre" class="keyWord_right">{{ unitTxt }}</span>
                <span
                  class="keyWord_right"
                  v-if="
                    item.prop === 'taps' ||
                    item.prop === 'installs' ||
                    item.prop === 'impressions' ||
                    item.prop === 'keywordId'
                  "
                  >{{ scope.row[item.prop] }}</span
                >
                <span class="keyWord_right" v-else>{{
                  scope.row[item.prop] | $toFixed(2)
                }}</span>
                <span class="keyWord_right" v-if="item.suf">{{
                  item.suf
                }}</span>
              </div>
              <!-- <span v-if="item.pre">{{ unitTxt }}</span>{{ scope.row[item.prop] }}<span v-if="item.suf">{{ item.suf }}</span> -->
            </div>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <div
      class="block"
      style="padding-top: 24px; display: flex; justify-content: flex-end"
    >
      <el-pagination
        :current-page="queryData.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 设置显示 -->

    <transfer-thead
      :default-th="thList"
      :th-list="thListCopy"
      :visible.sync="thVisible"
      @thListChange="handleSubThList"
    />
    <!-- 添加关键词 手动-->
    <word-box
      ref="addWordBox"
      :max-num="
        caInfo.dailyBudgetAmount
          ? caInfo.dailyBudgetAmount * 1
          : caInfo.budgetAmount * 1
      "
      :visible.sync="putShow"
      title="关键词"
      :fei-yong-show="true"
      :before-sub="handleClose"
      :appid="appid"
      :country-list="countryList"
      width="1200px"
      @handleSub="handleSubKey"
    >
      <div v-if="routeName === 'seriesOverview'">
        <p
          style="
            width: 360px;
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <span>添加至广告组</span>
          <em
            v-if="addAdList.length < allAdList.length"
            class="pointer"
            @click="handlePushAll"
            >添加全部</em
          >
          <em v-else class="pointer" @click="addAdList = []">移除全部</em>
        </p>
        <el-select
          v-model="addAdList"
          placeholder="请选择广告组"
          size="small"
          style="padding: 20px 0; width: 360px"
          multiple
        >
          <el-option
            v-for="(item, index) in allAdList"
            :key="item.adGroupId"
            :label="item.name"
            :value="item.adGroupId"
          />
        </el-select>
      </div>
    </word-box>
    <!-- 添加关键词  批量-->
    <up-load-words
      :is-negative="false"
      :visible.sync="dialogVisible"
      :max-num="
        caInfo.dailyBudgetAmount && caInfo.dailyBudgetAmount * 1 > 0
          ? caInfo.dailyBudgetAmount * 1
          : caInfo.budgetAmount
      "
      :before-upload="handleClose"
      @handleAddWords="handleSubKey"
    >
      <div
        v-if="routeName === 'seriesOverview'"
        style="width: 100%; padding-left: 24px"
      >
        <p
          style="
            width: 360px;
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <span>添加至广告组</span>
          <em
            v-if="addAdList.length < allAdList.length"
            class="pointer"
            @click="handlePushAll"
            >添加全部</em
          >
          <em v-else class="pointer" @click="addAdList = []">移除全部</em>
        </p>
        <el-select
          v-model="addAdList"
          placeholder="请选择广告组"
          size="small"
          style="padding: 20px 0; width: 360px"
          multiple
        >
          <el-option
            v-for="(item, index) in allAdList"
            :key="item.adGroupId"
            :label="item.name"
            :value="item.adGroupId"
          />
        </el-select>
      </div>
    </up-load-words>

    <!-- 关键词详情 -->
    <keyWordDetails
      v-if="oneKeyshow"
      :show.sync="oneKeyshow"
      :key-info="oneKeyInfo"
      :time-arr="timeArr"
    />

    <!-- 关键词高级搜索 -->
    <el-dialog
      title="高级筛选"
      :visible.sync="highSearchShow"
      width="600px"
      class="bottom-dia"
      @open="handlerOpenHighSearch"
    >
      <el-form :model="searchForm" :label-position="'top'" size="small">
        <el-row :gutter="80">
          <el-col :span="12">
            <el-form-item label="包含">
              <el-input
                v-model="searchForm.include"
                autocomplete="off"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="不包含">
              <el-input
                v-model="searchForm.denyWorder"
                autocomplete="off"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="花费">
              <intervalInput
                v-model="searchForm.localSpendAmount"
                :suffix-show="true"
              ></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="展示">
              <intervalInput
                v-model="searchForm.impressions"
                :precision="0"
              ></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="点击">
              <intervalInput
                v-model="searchForm.taps"
                :precision="0"
              ></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装">
              <intervalInput
                v-model="searchForm.installs"
                :precision="0"
              ></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平均每次点击费用">
              <intervalInput
                v-model="searchForm.avgCptAmount"
                :suffix-show="true"
              ></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平均每次转化费用">
              <intervalInput
                v-model="searchForm.avgCpaAmount"
                :suffix-show="true"
              ></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="点击率">
              <intervalInput
                v-model="searchForm.ttr"
                :suffix-show="true"
                suffix-txt="%"
              ></intervalInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转化率">
              <intervalInput
                v-model="searchForm.conversionRate"
                :suffix-show="true"
                suffix-txt="%"
              ></intervalInput>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer flex">
        <em style="font-size: 14px" @click="resetSearForm">重置</em>
        <div>
          <el-button class="cancel-btn" @click="highSearchShow = false"
            >取 消</el-button
          >
          <el-button type="success" @click="handlerHighSearch">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tableBatchHandle from "../../components/table-batch-handle/index.vue";
import transferThead from "../../components/transferThead.vue";
import wordBox from "@/components/word-box.vue";
import adjustBox from "@/components/adjustBox/index.vue";
import upLoadWords from "./upLoadWords.vue";
import keyWordDetails from "./keyWordDetails.vue";
import {
  findReportKeywordList, // 查询广告组下的关键词表格
  findReportKeywordListTotal, // 查询总计数据
  downloadKeywordCsv, // 下载关键词表格
  addKeyWords, // 添加关键词
  modifyKeyWords, // 修改关键词
  modifyPrice, // 批量调整关键词出价
} from "@/api/keyWord.js";

export default {
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector("input").focus();
      },
    },
  },
  components: {
    tableBatchHandle,
    transferThead,
    wordBox,
    upLoadWords,
    keyWordDetails,
    adjustBox,
  },

  data() {
    return {
      highSearchShow: false, // 高级筛选的弹框显示状态
      searchForm: {
        include: "", // 包含
        denyWorder: "", // 不包含
        localSpendAmount: {
          // 花费
          min: undefined,
          max: undefined,
        },
        impressions: {
          min: undefined,
          max: undefined,
        }, // 展示
        installs: {
          min: undefined,
          max: undefined,
        }, // 安装||下载
        avgCptAmount: {
          min: undefined,
          max: undefined,
        }, // cpt
        avgCpaAmount: {
          min: undefined,
          max: undefined,
        }, // cpa
        ttr: {
          min: undefined,
          max: undefined,
        }, // 点击率
        conversionRate: {
          min: undefined,
          max: undefined,
        }, // 转化率
      },
      isEdit: false,
      adJustLoading: false, // 调整出价的盒子的加载状态
      addAdList: [], // 要添加关键词到哪个广告组，

      showStatus: true,
      index_number: "",
      oneKeyshow: false,
      oneKeyInfo: {},
      popoNunmberIsTrue: true,
      ruleTxt: "您的出价必须至少为0.01",
      loading: true,
      loadingText: "数据加载中，请稍候",
      dialogVisible: false,
      csvUrl: "", // 模板下载路径
      /* 批量修改最高每次点击费用*/
      popoNunmber: undefined,
      popoShow: false,
      // 关键词添加
      putShow: false,
      keywords: [],
      // 关键词上传
      thVisible: false, // 设置字段的显示
      checkedList: [], // 选中的
      tableData: '',
      totalData: [],
      total: 0,
      queryData: {
        teamId: this.$store.state.team.teamId || "",
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime, // 时区比UTC时间少几个小时
        currencyType:
          this.$route.query.currencyType || this.$store.state.user.unit,
        adgroupId:
          this.$route.query.adgroupId || this.$route.query.adGroupId || "",
        campaignId: this.$route.query.campaignId || "",
        startTime: this.$store.state.overview.timeObj.overViewTime.startTime,
        endTime: this.$store.state.overview.timeObj.overViewTime.endTime,
        name: "",
        order: "descending",
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        pageNum: 1,
        pageSize: 10,
        prop: "status", // 选择项
        status: "",
        matchType: "",
        reportKeywordListCondition: {
          localSpendAmountMin: undefined,
          localSpendAmountMax: undefined,
          impressionsMin: undefined,
          impressionsMax: undefined,
          tapsMin: undefined,
          tapsMax: undefined,
          installsMin: undefined,
          installsMax: undefined,
          avgCptAmountMin: undefined,
          avgCptAmountMax: undefined,
          avgCpaAmountMin: undefined,
          avgCpaAmountMax: undefined,
          ttrMin: undefined,
          ttrMax: undefined,
          conversionRateMin: undefined,
          conversionRateMax: undefined,
          denyWorder: "",
          include: "",
        },
      },
      searchForm: {
        include: "",
        denyWorder: "",
        localSpendAmount: {
          min: undefined,
          max: undefined,
        },
        impressions: {
          min: undefined,
          max: undefined,
        },
        taps: {
          min: undefined,
          max: undefined,
        },
        installs: {
          min: undefined,
          max: undefined,
        },
        avgCptAmount: {
          min: undefined,
          max: undefined,
        },
        avgCpaAmount: {
          min: undefined,
          max: undefined,
        },
        ttr: {
          min: undefined,
          max: undefined,
        },
        conversionRate: {
          min: undefined,
          max: undefined,
        },
      },

      thListCopy: [], // 表头
      thList: [
        {
          prop: "keywordId", // 属性
          label: "关键词ID", // 名称
          show: false, // 是否显示，
          sort: false, // 是否可以排序
          width: 180, // 宽度
        },
        {
          prop: "matchType", // 属性
          label: "匹配类型", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          width: 240, // 宽度
        },
        {
          prop: "localSpendAmount", // 属性
          label: "花费", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
        },

        {
          prop: "impressions", // 属性
          label: "展示", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "taps", // 属性
          label: "点击", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "bidAmount", // 属性
          label: "最高每次点击费用出价", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          showSta: true, // 是否可点击
          pre: "$",
          width: 220, // 宽度
        },

        {
          prop: "installs", // 属性
          label: "安装", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "avgCpaAmount", // 属性
          label: "平均CPA", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
        },
        {
          prop: "avgCptAmount", // 属性
          label: "平均CPT", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          pre: "$",
        },

        {
          prop: "ttr", // 属性
          label: "点击率", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          suf: "%",
        },
        {
          prop: "conversionRate", // 属性
          label: "转化率", // 名称
          show: true, // 是否显示，
          sort: true, // 是否可以排序
          suf: "%",
        },
        {
          prop: "newDownloads", // 属性
          label: "新增下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "redownloads", // 属性
          label: "重复下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
        },
        {
          prop: "latOffinstalls", // 属性
          label: "开启LAT下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
          width: 200, // 宽度
        },
        {
          prop: "latOninstalls", // 属性
          label: "关闭LAT下载", // 名称
          show: false, // 是否显示，
          sort: true, // 是否可以排序
          width: 200, // 宽度
        },
      ],
    };
  },
  computed: {
    // 选择的开始时间与结束时间
    timeObj() {
      return this.$store.state.overview.timeObj.overViewTime;
    },
    routeName() {
      return this.$route.name;
    },
    appid() {
      const campaignId =
        this.$route.query.campaignId || this.$route.query.campaignid || "";
      const list = this.$store.state.overview.allCa;
      const index = list.findIndex((item) => {
        return campaignId * 1 === item.campaignId * 1;
      });
      if (index !== -1) {
        return this.$store.state.overview.allCa[index].adamId;
      } else {
        return "";
      }
    },
    timeZone() {
      return this.$store.state.user.timeZone;
    },

    countryList() {
      const campaignId =
        this.$route.query.campaignId || this.$route.query.campaignid || "";
      const list = this.$store.state.overview.allCa;
      const index = list.findIndex((item) => {
        return campaignId * 1 === item.campaignId * 1;
      });
      const countrys =
        this.$store.state.overview.allCa[index].countriesOrRegions;

      if (index !== -1) {
        if (countrys && countrys.length) {
          const str = countrys.substring(1, countrys.length - 1);

          return str.split(",");
        } else {
          return [];
        }
      } else {
        return [];
      }
    },

    selectBtnShow() {
      if (
        this.$route.query.uuid &&
        (this.$route.query.orgId || this.$route.query.orgid)
      ) {
        const index = this.$store.state.overview.allAc.findIndex((item) => {
          return item.uuid === this.$route.query.uuid;
        });
        if (
          this.$store.state.overview.allAc[index].roleName === "invalid_client"
        ) {
          return false;
        }
        const i = this.$store.state.overview.allAc[index].org.findIndex(
          (item) => {
            return (
              item.orgId === this.$route.query.orgId * 1 ||
              item.orgId === this.$route.query.orgid * 1
            );
          }
        );
        const orgRole = this.$store.state.overview.allAc[index].org[i].roleName;
        return (
          orgRole !== "API Read Only" &&
          orgRole !== "invalid_client" &&
          !this.$isReadOnly(this.$store.state.user.userInfo.roleName)
        );
      } else {
        return !this.$isReadOnly(this.$store.state.user.userInfo.roleName);
      }
    },
    unitTxt() {
      const unit = this.$store.state.user.unit;
      this.$forceUpdate();
      return unit === "RMB" ? "￥" : "$";
    },
    // 广告系列详情
    caInfo() {
      const arr = this.$store.state.overview.allCa;
      const index = arr.findIndex((item) => {
        return item.campaignId * 1 === this.$route.query.campaignId * 1;
      });
      return arr[index];
    },

    adInfo() {
      if (this.$route.name === "seriesOverview") {
        return {
          displayStatus: this.caInfo.displayStatus,
        };
      }
      const arr = this.$store.state.overview.allAd;
      const index = arr.findIndex((item) => {
        return item.adGroupId * 1 === this.$route.query.adGroupId * 1;
      });
      return arr[index];
    },
    // 所有的广告组
    allAdList() {
      return this.$store.state.overview.allAd;
    },
  },
  watch: {
    timeObj: {
      handler: function (newval, oldval) {
        if (newval) {
          this.queryData.pageNum = 1;
          this.queryData.startTime = newval.startTime;
          this.queryData.endTime = newval.endTime;
          this.findReportKeywordList();
        }
      },
      immediate: true,
      deep: true,
    },
    timeZone: {
      deep: true,
      handler: function (newV, oldV) {
        this.queryData.pageNum = 1;
        this.findReportKeywordList();
      },
    },
    tableData(newV) {
      this.tableData = newV;
    },
  },
  mounted() {
    // 表头
    if (this.$route.name !== "seriesOverview") {
      if (localStorage.getItem("3yData_ad_keyWords_Thlist")) {
        this.thListCopy = JSON.parse(
          localStorage.getItem("3yData_ad_keyWords_Thlist")
        );
      } else {
        this.thListCopy = JSON.parse(JSON.stringify(this.thList));
      }
    } else {
      if (localStorage.getItem("3yData_ca_keyWords_Thlist")) {
        this.thListCopy = JSON.parse(
          localStorage.getItem("3yData_ca_keyWords_Thlist")
        );
      } else {
        this.thListCopy = JSON.parse(JSON.stringify(this.thList));
      }
    }

    this.findReportKeywordList();
  },

  methods: {
    // 打开高级筛选显示框
    handlerOpenHighSearch() {
      const searchForm = this.searchForm;
      for (const key in searchForm) {
        if (key === "include") {
          this.searchForm.include =
            this.queryData.reportKeywordListCondition.include;
        } else if (key === "denyWorder") {
          this.searchForm.denyWorder =
            this.queryData.reportKeywordListCondition.denyWorder;
        } else {
          this.searchForm[key].max = this.queryData.reportKeywordListCondition[
            key + "Max"
          ]
            ? this.queryData.reportKeywordListCondition[key + "Max"]
            : undefined;
          this.searchForm[key].min = this.queryData.reportKeywordListCondition[
            key + "Min"
          ]
            ? this.queryData.reportKeywordListCondition[key + "Min"]
            : undefined;
        }
      }
    },
    // 重置高级筛选
    resetSearForm() {
      this.searchForm = {
        include: "",
        denyWorder: "",
        localSpendAmount: {
          min: undefined,
          max: undefined,
        },
        impressions: {
          min: undefined,
          max: undefined,
        },
        taps: {
          min: undefined,
          max: undefined,
        },
        installs: {
          min: undefined,
          max: undefined,
        },
        avgCptAmount: {
          min: undefined,
          max: undefined,
        },
        avgCpaAmount: {
          min: undefined,
          max: undefined,
        },
        ttr: {
          min: undefined,
          max: undefined,
        },
        conversionRate: {
          min: undefined,
          max: undefined,
        },
      };
    },
    // 提交高级筛选
    handlerHighSearch() {
      const searchForm = this.searchForm;
      for (const key in searchForm) {
        if (key === "include") {
          this.queryData.reportKeywordListCondition.include =
            searchForm.include;
        } else if (key === "denyWorder") {
          this.queryData.reportKeywordListCondition.denyWorder =
            searchForm.denyWorder;
        } else {
          this.queryData.reportKeywordListCondition[key + "Max"] = this
            .searchForm[key].max
            ? this.searchForm[key].max
            : undefined;
          this.queryData.reportKeywordListCondition[key + "Min"] = this
            .searchForm[key].min
            ? this.searchForm[key].min
            : undefined;
        }
      }
      this.highSearchShow = false;
      this.queryData.pageNum = 1;
      this.findReportKeywordList();
    },

    replaceKeyWord(word, type) {
      const str = word.replace(/\ /g, "&nbsp;");
      if (type === "EXACT") return "[" + str + "]";
      return str;
    },
    handlePushAll() {
      // console.log(this.addAdList, this.allAdList)
      if (this.allAdList.length) {
        this.addAdList = this.allAdList.map((item) => {
          return item.adGroupId;
        });
      } else {
        return false;
      }
    },

    headerStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 3) {
        return "center-align";
      }
    },
    handleClose() {
      if (this.routeName === "seriesOverview") {
        if (this.addAdList.length) return true;
        this.$message.closeAll();
        this.$message.error("请选择广告组");
        return false;
      }
      return true;
    },
    handleShowAddKey(type) {
      if (this.routeName === "seriesOverview" && this.allAdList.length === 0) {
        return this.$message.error("请先创建广告组");
      }
      if (type === "add") {
        this.putShow = true;
      } else {
        this.dialogVisible = true;
      }

      if (this.queryData.adgroupId) {
        this.addAdList = [this.queryData.adgroupId];
      } else {
        this.addAdList = [];
      }
    },
    isChange(value) {
      if (value) {
        this.isEdit = true;
      }
    },
    editYS(data, index) {
      this.showStatus = true;
      if (!this.isEdit) {
        return (this.index_number = -1);
      } else if (this.tableData[index].bidAmount * 1 > 1000) {
        this.$message.error("您的出价不得高于$1000.00");
        this.index_number = -1;
        this.findReportKeywordList();
        this.isEdit = false;
      } else if (
        this.tableData[index].bidAmount * 100 < 1 ||
        this.tableData[index].bidAmount === undefined ||
        this.tableData[index].bidAmount === ""
      ) {
        this.$message.error("您的出价必须至少为 $0.01");
        this.index_number = -1;
        this.findReportKeywordList();
        this.isEdit = false;
      } else if (
        this.caInfo.dailyBudgetAmount * 1 === 0 &&
        this.tableData[index].bidAmount * 1 > this.caInfo.budgetAmount * 1
      ) {
        this.index_number = -1;
        this.$message.error(
          "您的出价不能大于预算" + (this.caInfo.budgetAmount * 1).toFixed(2)
        );
        this.findReportKeywordList();
        this.isEdit = false;
      } else if (
        this.caInfo.dailyBudgetAmount * 1 > 0 &&
        this.tableData[index].bidAmount * 1 > this.caInfo.dailyBudgetAmount * 1
      ) {
        this.index_number = -1;
        this.$message.error(
          "您的出价不能大于每日预算" +
            (this.caInfo.dailyBudgetAmount * 1).toFixed(2)
        );
        this.findReportKeywordList();
        this.isEdit = false;
      } else {
        const arr = [];
        arr.push({
          teamId: this.$store.state.team.teamId || "",
          currencyType: this.$route.query.unit || this.$store.state.user.unit,
          campaignId:
            this.$route.query.campaignId || this.$route.query.campaignid || "",
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          adGroupId: data.adGroupId,
          keywords: [
            {
              id: data.keywordId,
              bidAmountNub: this.tableData[index].bidAmount,
            },
          ],
        });
        this.modifyKeyWords(arr);
      }
    },
    /* 打开编辑框 */
    openEdit(name, index) {
      this.index_number = index;
      if (name === "bidAmount") {
        this.tableData.forEach((item, i) => {
          if (index === i) {
            this.showStatus = false;
          }
        });
      }
    },
    handleFocus(row) {},
    handleOneKeyShow(data) {
      this.oneKeyshow = true;
      this.oneKeyInfo = JSON.parse(JSON.stringify(data));
    },
    // 勾选数据
    tableCheckChange(data) {
      this.checkedList = JSON.parse(JSON.stringify(data));
    },

    /* 批量操作 */

    // 批量开始与暂停
    handleBatchStartOrPause(type) {
      const arr = this.checkedList.map((item) => {
        const obj = {
          teamId: this.$store.state.team.teamId,
          currencyType: this.$route.query.unit || this.$store.state.user.unit,
          campaignId:
            this.$route.query.campaignId || this.$route.query.campaignid || "",
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          adGroupId: item.adGroupId,
          keywords: [
            {
              id: item.keywordId,
              status: type,
            },
          ],
        };
        return obj;
      });
      this.modifyKeyWords(arr);
    },

    // 批量修改匹配类型
    handleBatchMatchType(type) {
      const arr = this.checkedList.map((item) => {
        const obj = {
          teamId: this.$store.state.team.teamId || "",
          currencyType: this.$route.query.unit || this.$store.state.user.unit,
          campaignId:
            this.$route.query.campaignId || this.$route.query.campaignid || "",
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          adGroupId: item.adGroupId,
          keywords: [
            {
              id: item.keywordId,
              matchType: type,
            },
          ],
        };
        return obj;
      });
      this.modifyKeyWords(arr);
    },
    handlerPopoShow() {
      this.$nextTick(() => {
        this.$refs["adjustBox"] && this.$refs["adjustBox"].reset();
      });
    },

    // 批量确认修改每次最高点击费用
    changeFeiYong(data) {
      if (
        this.caInfo.dailyBudgetAmount &&
        data.num > this.caInfo.dailyBudgetAmount * 1 &&
        data.type === "adjustment"
      ) {
        const msg =
          "不能超过广告系列的每日预算" +
          (this.caInfo.dailyBudgetAmount * 1).toFixed(2);
        this.$message({
          message: msg,
          type: "warning",
        });
      } else if (
        this.caInfo.budgetAmount &&
        data.num > this.caInfo.budgetAmount * 1 &&
        data.type === "adjustment"
      ) {
        const msg =
          "不能超过广告系列的总预算" +
          (this.caInfo.budgetAmount * 1).toFixed(2);
        this.$message({
          message: msg,
          type: "warning",
        });
      } else {
        this.adJustLoading = true;

        const arr = this.checkedList.map((item) => {
          const obj = {
            teamId: this.$store.state.team.teamId || "",
            currencyType: this.$route.query.unit || this.$store.state.user.unit,
            campaignId:
              this.$route.query.campaignId ||
              this.$route.query.campaignid ||
              "",
            orgId: this.$route.query.orgId || "", // 如果是自助投放为空
            uuid: this.$route.query.uuid || "",
            aId: this.$route.query.aId || this.$route.query.aid || "",
            adGroupId: item.adGroupId,
            keywords: [
              {
                id: item.keywordId,
                bidAmountNub: item.bidAmount,
              },
            ],
          };
          return obj;
        });

        const dataObj = {
          type: data.type,
          nub: data.num,
          campaignGroupId:
            this.$route.query.serialId || this.$route.query.serialid || 0,
          campaignId:
            this.$route.query.campaignId || this.$route.query.campaignid || "",
          teamId: this.$store.state.team.teamId || "",
          currencyType: this.$route.query.unit || this.$store.state.user.unit,
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          advInfolist: arr,
        };

        this.modifyPrice({ ...dataObj });
      }
    },

    async modifyPrice(obj) {
      const res = await modifyPrice(obj);
      this.adJustLoading = false;
      if (res.data.code * 1 === 20000 && res.data.flag) {
        this.$message({
          type: "success",
          message: res.data.message || "出价调整中",
        });
        this.loading = true;
        this.loadingText = "修改完成，数据正在更新中，请稍候";
        this.popoShow = false;
        setTimeout(() => {
          this.findReportKeywordList();
        }, 2500);
      } else {
        this.$message.error(res.data.message || "调整出价失败");
      }
    },

    async modifyKeyWords(data) {
      const res = await modifyKeyWords(data);
      if (res.data.code && res.data.code === 20000) {
        this.index_number = -1;
        this.isEdit = false;
        this.loading = true;
        this.loadingText = "修改完成，数据正在更新中，请稍候";

        setTimeout(() => {
          this.findReportKeywordList();
        }, 2500);
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器出错，请稍后重试");
      }
    },

    // 添加关键词
    async handleSubKey(data) {
      if (!data.length) return false;

      const list =
        this.routeName === "seriesOverview"
          ? this.addAdList
          : [this.$route.query.adGroupId];
      if (!list.length) {
        this.$message.closeAll();
        return this.$message.error("请选择广告组");
      }

      const arr = list.map((item) => {
        const obj = {
          teamId: this.$store.state.team.teamId || "",
          campaignId:
            this.$route.query.campaignId || this.$route.query.campaignid || "",
          adGroupId: item,
          orgId: this.$route.query.orgId || "", // 如果是自助投放为空
          uuid: this.$route.query.uuid || "",
          aId: this.$route.query.aId || this.$route.query.aid || "",
          userId: this.$store.state.user.userInfo.userId,
          keywords: JSON.parse(JSON.stringify(data)),
          currencyType:
            this.$route.query.currencyType || this.$store.state.user.unit,
        };
        return obj;
      });
      const res = await addKeyWords(arr);
      this.$refs["addWordBox"].wordsData = [];
      if (res.data.code && res.data.code === 20000) {
        this.loading = true;
        this.loadingText = "添加完成，数据更新中。请稍候";
        setTimeout(() => {
          this.findReportKeywordList();
          this.$emit("addKeyWord");
        }, 4000);
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器错误，请稍后重试");
      }
    },

    handleSizeChange(index) {
      this.queryData.pageSize = index;
      this.queryData.pageNum = 1;
      this.findReportKeywordList();

    },
    handleCurrentChange(index) {
      this.queryData.pageNum = index;
      this.findReportKeywordList();
    },
    queryDataChange() {
      this.queryData.pageNum = 1;
      this.findReportKeywordList();
    },

    // 排序变化
    tableSortChange(obj) {
      if (!obj.order) {
        this.queryData.prop = "status";
        this.queryData.order = "descending";
      } else {
        this.queryData.prop = obj.prop;
        this.queryData.order = obj.order;
      }
      this.queryData.pageNum = 1;
      this.findReportKeywordList();
    },

    // 获取关键词列表
    async findReportKeywordList() {
      this.loading = true;
      /* console.log(this.loading, '关键词加载') */
      this.loadingText = "数据加载中，请稍候";
      const res = await findReportKeywordList({
        ...this.queryData,
        teamId: this.$store.state.team.teamId || "",
        currencyType:
          this.$route.query.currencyType || this.$store.state.user.unit,
      });
      if (res.data.code === 20000) {
        this.total = res.data.data.total;
        this.tableData= res.data.data.list;
         this.$forceUpdate()
        this.tableData.forEach((item) => {
          item.localSpendAmount = item.localSpendAmount * 1;
          item.avgCpaAmount = item.avgCpaAmount * 1;
          item.avgCptAmount = item.avgCptAmount * 1;
        });
        this.loading = false;
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器错误，请稍后重试");
        this.loading = false;
      }
      this.findReportKeywordListTotal();
    },

    // 去广告组详情
    handlePush(id) {
      this.$router.push({
        name: "groupOverview",
        query: {
          ...this.$route.query,
          adGroupId: id,
        },
      });
    },

    // 对远程获取到的统计数据做出处理
    returnTotal(param) {
      const {
        columns,
        // data
      } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "总计";
          return;
        } else {
          for (const key in this.totalData) {
            if (key === column.property) {
              switch (key) {
                case "bidAmount":
                  sums[index] =
                    this.unitTxt +
                    (this.totalData[key]
                      ? (this.totalData[key] * 1).toFixed(2)
                      : 0.0);
                  break;
                case "localSpendAmount":
                  sums[index] =
                    this.unitTxt +
                    (this.totalData[key]
                      ? (this.totalData[key] * 1).toFixed(2)
                      : 0.0);
                  break;
                case "avgCpaAmount":
                  sums[index] =
                    this.unitTxt +
                    (this.totalData[key]
                      ? (this.totalData[key] * 1).toFixed(2)
                      : 0.0);
                  break;
                case "avgCptAmount":
                  sums[index] =
                    this.unitTxt +
                    (this.totalData[key]
                      ? (this.totalData[key] * 1).toFixed(2)
                      : 0.0);
                  break;
                case "avgCpmAmount":
                  sums[index] =
                    this.unitTxt +
                    (this.totalData[key]
                      ? (this.totalData[key] * 1).toFixed(2)
                      : 0.0);
                  break;
                case "ttr":
                  sums[index] =
                    (this.totalData[key]
                      ? (this.totalData[key] * 1).toFixed(2)
                      : 0.0) + "%";
                  break;
                case "conversionRate":
                  sums[index] =
                    (this.totalData[key]
                      ? (this.totalData[key] * 1).toFixed(2)
                      : 0.0) + "%";
                  break;

                default:
                  sums[index] = this.totalData[key];
                  break;
              }
            }
          }
        }
      });

      return sums;
    },

    async findReportKeywordListTotal() {
      this.loading = true
      this.loadingText = "数据加载中，请稍候";
      const res = await findReportKeywordListTotal({
        ...this.queryData,
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        teamId: this.$store.state.team.teamId || "",
        currencyType:
          this.$route.query.currencyType || this.$store.state.user.unit,
        campaignId: this.$route.query.campaignId || "",
      });
      if (res.data.code === 20000) {
        this.$forceUpdate()
        this.totalData = res.data.data[0];
        this.loading = false
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器错误，请稍后重试");
        this.loading = false
      }
    },

    // 设置显示字段
    thShowChange() {
      this.thVisible = true;
    },

    handleSubThList(arr) {
      this.thListCopy = JSON.parse(JSON.stringify(arr));
      if (this.routeName !== "seriesOverview") {
        localStorage.setItem("3yData_ad_keyWords_Thlist", JSON.stringify(arr));
      } else {
        localStorage.setItem("3yData_ca_keyWords_Thlist", JSON.stringify(arr));
      }

      this.$("keyTable").doLayout();
      this.$forceUpdate();
    },
    // 导出数据
    async dowLoadCsv() {
      if (this.total < 1) {
        this.$message.closeAll();
        this.$message.error("请先添加添关键词");
        return false;
      }
      const res = await downloadKeywordCsv({
        ...this.queryData,
        pageNum: 1,
        pageSize: this.total,
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        teamId: this.$store.state.team.teamId || "",
        currencyType:
          this.$route.query.currencyType || this.$store.state.user.unit,
        campaignId: this.$route.query.campaignId || "",
      });

      if (!res.data.message) {
        const blob = new Blob(["\ufeff" + res.data], {
          type: "text/csv,charset=UTF-8",
        });
        const that = this;
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.setAttribute("href", objectUrl);
        a.setAttribute(
          "download",
          "YYY_DATA_关键词_" +
            that.queryData.startTime +
            "_" +
            this.queryData.endTime +
            ".csv"
        );
        a.click();
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "导出数据失败，请稍后重试");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../components/handle.scss";
// 设置表格总计样式
div /deep/.el-table__footer-wrapper td.el-table__cell {
  position: relative !important;
  left: -12px !important;
}
.price_div {
  padding: 2px;
  cursor: pointer;
  border-radius: 2px;
}

.price_div:hover {
  border: 1px solid #e0e2e7;
  border-radius: 2px;
}

.series-table {
  margin-top: 24px;

  /deep/ thead {
    th.el-table__cell.is-right > .cell {
      padding-left: 10px !important;
      padding-right: 24px;

      .caret-wrapper {
        position: absolute;
        top: 50%;
        right: 0;
        transform: translateY(-46%);
      }
    }
  }

  /deep/ .el-table__body {
    background: #ffffff;
    .el-table__cell.is-right > .cell {
      padding-right: 24px !important;
    }
  }

  // /deep/ .el-table__footer-wrapper  .el-table__cell.is-right>.cell{
  //   padding-right: 24px !important;
  // }
  /deep/ .del-row {
    background: rgba(57, 68, 78, 0.1);

    td,
    .cell {
      background: transparent !important;
    }
  }
}
</style>
